<template>
  <el-dialog :title="$t('iot.programSend')" :visible.sync="visible" width="1280px" top="5vh" append-to-body>
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="name">
        <el-input v-model="queryParams.name" :placeholder="$t('iot.enterProgramName')" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('common.search') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8"><right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/></el-row>
    <el-row>
      <el-table @row-click="clickRow" ref="table" :data="hgitemsList" height="520px">
        <el-table-column label="" width="35" align="center" prop="_selection" :resizable="false">
          <template #default="{ row }">
            <el-radio v-model="selectedRowCurrent" :label="row" @change="handleRadioChange">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column :label="$t('iot.customer')" align="center" prop="nickName" width="155"/>
        <el-table-column :label="$t('iot.project')" align="center" prop="projectname" width="155"/>
        <el-table-column :label="$t('iot.programNo')" align="center" prop="id" />
        <el-table-column :label="$t('iot.programName')" align="center" prop="name" width="125"/>
        <el-table-column :label="$t('iot.width')" align="center" prop="width" />
        <el-table-column :label="$t('iot.height')" align="center" prop="height" />
        <el-table-column :label="$t('iot.fontSize')" align="center" prop="fsize" />
        <el-table-column :label="$t('iot.textContent')" align="center" prop="remark" width="161" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('common.createTime')" align="center" prop="createTime" width="156">
          <template slot-scope="scope">{{scope.row.createTime}}</template>
        </el-table-column>
        <el-table-column :label="$t('iot.creator')" align="center" prop="createBy"/>
        <el-table-column :label="$t('common.updateTime')" align="center" prop="updateTime" width="156">
          <template slot-scope="scope">{{scope.row.updateTime||$t('iot.notUpdated')}}</template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
    </el-row>
    <div slot="footer" class="el-dialog--center">
      <el-button type="primary" icon="el-icon-upload" @click="handleSelectDisplay">{{ $t('iot.send') }}</el-button>
      <el-button type="info" icon="el-icon-close" @click="closeSelectDisplay">{{ $t('common.cancel') }}</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { listHgitems } from "@/api/iot/hgitems";
import Template from '@/views/iot/template/index.vue'
import request from '@/utils/request'
export default {
  data() {
    return {
      showSearch: true,
      selectedRows: [], // 用于存储选中的设备
      // 遮罩层
      visible: false,
      selectedRowCurrent: null,
      // 总条数
      total: 0,
      // 未授权用户数据
      hgitemsList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null
      }
    };
  },
  methods: {
    show(boxNos) {
      console.log('boxNos:', boxNos);
      this.selectedRows = boxNos;
      console.log('selectedRows:', this.selectedRows);
      this.getList();
      this.visible = true;
    },
    getStateImags(status) {
      return status==='1'?require('@/assets/bigScreen/img/wifion.png'):require('@/assets/bigScreen/img/wifi.png');
    },
    getStatusImage(status) {
      // 确保比较的是字符串类型
      return status==='1'?require('@/assets/bigScreen/img/light_on.png'):require('@/assets/bigScreen/img/light_off.png');
    },
    getLampErrorImage(status) {
      // 确保比较的是字符串类型
      return status==='0'?require('@/assets/bigScreen/img/wx1.png'):require('@/assets/bigScreen/img/zc1.png');
    },
    clickRow(row, column, event) {
      if (column.property !== '_selection') {
        this.selectedRowCurrent = row
        console.log('clickRow:', row)
      }
    },
    handleRadioChange(row) {
      console.log('selectRow:', row)
      this.selectedRowCurrent = row
    },
    handleSelectionChange(selection) {
      this.userIds = selection.map(item => item.userId);
    },
    getList() {
      listHgitems(this.queryParams).then(response => {
        this.hgitemsList = response.rows;
        this.total = response.total;
      });
    },
    closeSelectDisplay() {
      this.selectedRowCurrent = null;
      this.visible = false;
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    publish(snThing) {
      console.log('1:', JSON.stringify(snThing));
      return request({
        url: '/mqtt/backclient/xpublishxixun',
        method: 'post',
        data: snThing,
        headers: {
          'Content-Type': 'application/json'
        }
      })
    },
    handleSelectDisplay() {
      const userIds = this.selectedRowCurrent;
      if (userIds == null) {
        this.$modal.msgError(this.$t('iot.selectProgramToSend'));
        return;
      }
      const loadingMessage = this.$message({
        message: `<strong style="color: #f56c6c; font-weight: bold;">${this.$t('iot.programSending')}</strong>`,
        type: 'info',
        duration: 0, // 设置为0表示不会自动关闭
        showClose: true,
        dangerouslyUseHTMLString: true
      });
      const selectedRows = this.selectedRows;
      const requests = selectedRows.map(row => {
        if (!row.dsId) {
          this.$message.error(this.$t('iot.selectedDeviceMissingNo'));
          return null;
        }
        return this.publish({
          type: 7,
          id: row.id,
          provideType: row.dsType,
          sno: row.dsId,
          productKey: "commandXixunPlayer",
          fn: "PlayXixunTask",
          faHgitems: {
            attachfile: userIds.attachfile,
            fsize: userIds.fsize,
            height: userIds.height,
            images: userIds.images,
            imgPTime: userIds.imgPTime,
            name: userIds.name,
            remark: userIds.remark,
            textPTime: userIds.textPTime,
            width: userIds.width
          }
        });
      }).filter(request => request !== null);
      Promise.all(requests).then(results => {
          loadingMessage.close();
          let msgsuccess = "", msgfail = "", jsonArray = [];
          results.forEach(item=>{jsonArray.push(item.data);});
          const result = jsonArray.reduce((acc, obj) => {return { ...acc, ...obj };},{});
          for (const [key, value] of Object.entries(result)) {
              if(value){
                msgsuccess+=key+",";
              }else{
                msgfail+=key+",";
              }
          }
          const msgsuccrslt = msgsuccess.substring(0,msgsuccess.length-1);
          const msgfailrslt = msgfail.substring(0,msgfail.length-1);
          if(msgsuccess.length>0&&msgfail.length>0){
            this.$message.warning(this.$t('iot.sendSuccessControlCards') + msgsuccrslt + this.$t('iot.sendFailedControlCards') + msgfailrslt,{duration:15000});
          }
          if(msgsuccess.length>0&&msgfail.length==0){
            this.$modal.msgSuccess(this.$t('iot.sendSuccessControlCards') + msgsuccrslt,{duration:18000});
          }
          if(msgsuccess.length==0&&msgfail.length>0){
            this.$message.warning(this.$t('iot.sendFailedControlCards') + msgfailrslt,{duration:15000});
          }
          this.selectedRowCurrent = null;
          this.visible = false;
          this.$emit("ok");
      }).catch(error => {
          loadingMessage.close();
          console.error(error);
      });
    }
  }
};
</script>
